package com.zcf.controller;

import com.zcf.common.utils.MD5Util;
import com.zcf.mapper.DiningMapper;
import com.zcf.mapper.StoreMapper;
import com.zcf.mapper.UserMapper;
import com.zcf.mappers.Demo;
import com.zcf.pojo.*;
import com.zcf.utils.Hutool;
import com.zcf.utils.UploadImgUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zcf.common.json.Body;
import com.zcf.mapper.SubordinateMapper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 商家抽成表 前端控制器
 * </p>
 *
 * @author loupeng
 * @since 2018-12-25
 */
@Controller
@RequestMapping("/subordinate")
@ResponseBody
@CrossOrigin
public class SubordinateController {
    @Autowired
    SubordinateMapper subordinateMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private DiningMapper diningMapper;

    /**
     * 查询代理商对商家的抽成
     */
    @PostMapping("query")
    public Body query(String userId) {
        EntityWrapper<Subordinate> ew = new EntityWrapper<>();
        ew.eq("user_id", userId);
        Subordinate su = new Subordinate();
        su.setUserId(userId);
        List<Subordinate> lists = su.selectList(ew);
        if (lists.size() > 0) {
            return Body.newInstance(lists);
        }
        return Body.newInstance();
    }

    /**
     * 新增img
     */
    @PostMapping("addimg")
    @RequestMapping("/addimg")
    public Body addimg(MultipartFile[] files) throws Exception{
        if (files != null && !"".equals(files)) {
            try {
                String fan = UploadImgUtils.uploadFiles(files);
                return Body.newInstance(fan);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Body.newInstance(501, "照片不能为空");

    }
    /**
     * 新增用户
     */
    @PostMapping("add")
    @RequestMapping("/add")
    public Body add(Subordinate subordinate, HttpServletRequest request) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        EntityWrapper<Subordinate> ew = new EntityWrapper<>();
        ew.eq("din_id", subordinate.getDinId());
        String userId = Hutool.getId();
        User user = new User();
        user.setName(Hutool.getRandomString(8));
        user.setPhone(request.getParameter("phone"));
        user.setTime(time);
        user.setId(userId);
        user.setHead("http://hbtianshou.com/images/images/2f25ba30c762454a9e3281f4ea87cfe7.jpeg");
        // MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(request.getParameter("password")));
        user.setRole(2);
        Integer insert = userMapper.insert(user);

        Dining dining = new Dining();

        Store store = new Store();
        store.setUserId(userId);
        store.setId(Hutool.getId());
        store.setName(request.getParameter("name"));
        store.setRange(request.getParameter("range"));
        store.setPhone(request.getParameter("phone"));
        store.setAddress(request.getParameter("address"));

        store.setStatus(1);
        store.setTime(time);
        String longitude = "", latitude = "";
        // 根据地址获取经纬度
        Demo demo = new Demo();
        try {

            Object s = demo.gaodeditu(request.getParameter("address"));
            String appid = s.toString();
            String lon[] = appid.split(",");
            for (int i = 0; i < lon.length; i++) {
                String string = lon[i];
                if (i == 0) {
                    longitude = string;
                } else {
                    latitude = string;
                }
            }
            store.setLongitude(longitude);
            store.setLatitude(latitude);
        } catch (Exception exception) {
            return Body.newInstance(501, "地址格式错误，请填写xx省xx市xx区 或者 xx县再加详细地址！");
        }

        if (request.getParameter("notice") == null || request.getParameter("notice").equals("")) {
        } else {
            store.setNotice(request.getParameter("notice"));
        }
        Integer id = storeMapper.insert(store);


        Store store2 = new Store();
        store2.setId(store.getId());
        Store one = storeMapper.selectById(store2);
        if (one != null && !"".equals(one)) {
            one.setStatus(2);
            Integer b = storeMapper.updateById(one);
            if (b > 0) {
                Riding riding = new Riding();
                EntityWrapper<Riding> e = new EntityWrapper<>();
                e.eq("user_id", one.getId());
                riding = riding.selectOne(e);
                if (riding != null) {
                    riding.deleteById();
                }
                User user2 = new User();
                user2.setId(one.getUserId());
                User param = user2.selectById();

                Freight freight = new Freight();
                List<Freight> li = freight.selectAll();
                // 商家入驻
                Dining dining2 = new Dining();
                dining2.setAddress(one.getAddress());

//				JavaLarLng javaLarLng = new JavaLarLng();
//				String lng = javaLarLng.getLarLng(one.getAddress());
//				String lat = javaLarLng.getLarLngs(one.getAddress());
                // 经纬度
                dining2.setLongitude(one.getLongitude());
                dining2.setLatitude(one.getLatitude());
                dining2.setId(Hutool.getId());
                dining2.setImage(request.getParameter("img"));
                dining2.setUserId(one.getUserId());
                dining2.setTime(Hutool.parseDateToString());
                dining2.setBox(li.get(0).getBoxMoney());
                dining2.setFreight(li.get(0).getMoneys());
                dining2.setDiningName(one.getName());
                dining2.setDelivery(10.0);
                dining2.setPhone(one.getPhone());
                dining2.setGrade("5");
                dining2.setLargeId(one.getNotice());
                diningMapper.insert(dining2);

                // 代理抽成
                User users = new User();
                List<User> lists = users.selectAll();
                for (int i = 0; i < lists.size(); i++) {
                    String address = "";
                    EntityWrapper<Store> ew2 = new EntityWrapper<>();
                    address = lists.get(i).getAddress();
                    ew2.like("address", address);
                    Store stores = new Store();
                    stores = stores.selectOne(ew2);
                    if (store2 != null) {
                        Subordinate subordinate2 = new Subordinate();
                        subordinate2.setRegion(lists.get(i).getAddress());
                        subordinate2.setDinId(dining2.getId());
                        subordinate2.setProportion(10);
                        subordinate2.setUserId(lists.get(i).getId());
                        subordinate2.setSubordinateId(Hutool.getId());
                        subordinate2.setAddtime(Hutool.parseDateToString());
                        subordinate2.insert();

                        break;
                    }
                }
//				Subordinate subordinate = new Subordinate();
//				subordinate.setUserId(param.getId());
                if (param != null && !"".equals(param)) {
                    param.setStatus(2);
                    userMapper.updateById(param);
                    one.setDinId(dining2.getId());
                    return Body.newInstance("添加成功");
                }
                return Body.newInstance(501, "请用注册过的手机号");
            }
            return Body.newInstance(501, "更改状态失败");
        }
        return Body.newInstance(501, "用户不存在");
    }

    /**
     * 修改比例
     */
    @PostMapping("updates")
    @RequestMapping("/updates")
    public Body updates(Subordinate subordinate, HttpServletRequest request) {
        EntityWrapper<Subordinate> ew = new EntityWrapper<>();
        ew.eq("din_id", subordinate.getDinId());

        Subordinate subordinate2 = new Subordinate();
        subordinate2 = subordinate2.selectOne(ew);
        if (subordinate2 != null) {
            subordinate.setSubordinateId(subordinate2.getSubordinateId());
            Boolean glag = subordinate.updateById();

            if (glag) {

                Dining dining = new Dining();
                EntityWrapper<Dining> ew2 = new EntityWrapper<>();
                ew2.eq("id", subordinate.getDinId());
                dining = dining.selectOne(ew2);
                dining.setLargeId(subordinate.getRegion());
                try {
                    Demo demo = new Demo();
                    Object s = demo.gaodeditu(request.getParameter("address"));
                    String appid = s.toString();
                    String lon[] = appid.split(",");
                    String longitude = dining.getLongitude(), latitude = dining.getLatitude();
                    for (int i = 0; i < lon.length; i++) {
                        String string = lon[i];
                        if (i == 0) {
                            longitude = string;
                        } else {
                            latitude = string;
                        }
                    }

                    dining.setLongitude(longitude);
                    dining.setLatitude(latitude);
                } catch (Exception exception) {
                    return Body.newInstance(501, "地址格式错误，请填写xx省xx市xx区 或者 xx县再加详细地址！");
                }
                dining.setAddress(request.getParameter("address"));
                dining.setPhone(request.getParameter("phone"));
                dining.setDiningName(request.getParameter("name"));
                glag = dining.updateById();
                if (glag) {

                    return Body.newInstance("修改成功");
                }
            }
            return Body.newInstance("修改失败");
        }
        return Body.newInstance("修改失败");
    }
}
